/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package net.worlds.ui;

import net.worlds.ui.UI;
import java.awt.Component;
import java.awt.Point;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.tree.TreeNode;
import javax.swing.tree.TreePath;
import net.worlds.WorldsException;
import net.worlds.Main;
import net.worlds.object.GameObject;
import net.worlds.object.Script;


public class TreeMouseAdapter extends MouseAdapter{
    private void doPop(MouseEvent e)
    {
        TreeNode n = getTreeNodeAt(e.getPoint());
        if(n != null && n instanceof PartTreeNode)
        {
            TreePopupMenu m = new TreePopupMenu(((PartTreeNode)n).getObject());
            m.show((Component) e.getSource(),e.getX(), e.getY());
        }
    }
    private TreeNode getTreeNodeAt(Point p)
    {
        TreePath path =  Main.getApplet().getPartsTree().getPathForLocation(p.x, p.y);
        if(path == null)
            return null;
        TreeNode n = (TreeNode) path.getLastPathComponent();
        return n;
    }
    @Override
    public void mousePressed(MouseEvent e)
    {
        if(e.isPopupTrigger())
            doPop(e);
        if(e.getClickCount() == 2)
        {
            TreeNode n = getTreeNodeAt(e.getPoint());
            if(n != null && n instanceof PartTreeNode)
            {
                GameObject obj = (GameObject) ((PartTreeNode)n).getObject();
                if(obj instanceof Script)
                    try {
                    UI.editScript((Script) obj);
                } catch (WorldsException ex) {
                    Main.error(ex);
                }
            }
        }
    }
    @Override
    public void mouseReleased(MouseEvent e)
    {
        if(e.isPopupTrigger())
            doPop(e);
    }
}
